package com.example.amazing_wangjj.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.amazing_wangjj.mapper.SealSampleMapper;
import com.example.amazing_wangjj.pojo.SealSampleInfo;
import com.example.amazing_wangjj.service.SealSampleService;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 封样桶服务实现类
 * 实现封样桶相关的业务逻辑
 */
@Service
public class SealSampleServiceImpl extends ServiceImpl<SealSampleMapper, SealSampleInfo> implements SealSampleService {

    @Autowired
    private SealSampleMapper sealSampleMapper;

    /**
     * 检查企业今天是否已经申请过封样桶编码
     * @param companyCode 企业编码
     * @param applyTime 申请时间
     * @return 是否已经申请过
     */
    @Override
    public boolean hasAppliedToday(String companyCode, String applyTime) {
        // 检查applyTime是否为null
        if (applyTime == null || applyTime.isEmpty()) {
            return false;
        }
        // 构建查询条件，考虑不同格式的时间字符串
        String todayStr;
        if (applyTime.length() >= 10) {
            todayStr = applyTime.substring(0, 10); // 截取日期部分
        } else {
            todayStr = applyTime; // 使用完整字符串
        }
        List<SealSampleInfo> list = sealSampleMapper.selectList(
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<SealSampleInfo>()
                        .eq("company_code", companyCode)
                        .likeRight("apply_time", todayStr)
        );
        return list != null && !list.isEmpty();
    }

    /**
     * 保存封样桶信息并导出Excel文件
     * @param sealSampleInfos 封样桶信息列表
     * @return Excel文件路径
     */
    @Override
    public String saveAndExportExcel(List<SealSampleInfo> sealSampleInfos) {
        // 保存封样桶信息
        this.saveBatch(sealSampleInfos);
        
        // 生成Excel文件路径
        String timestamp = String.valueOf(System.currentTimeMillis());
        String filePath = "D:/export/seal_sample_" + timestamp + ".xlsx";
        
        // 确保目录存在
        File file = new File(filePath);
        File parentDir = file.getParentFile();
        if (parentDir != null && !parentDir.exists()) {
            parentDir.mkdirs();
        }
        
        // 使用Apache POI创建Excel文件并写入数据
        try (XSSFWorkbook workbook = new XSSFWorkbook();
             FileOutputStream outputStream = new FileOutputStream(filePath)) {
            
            // 创建工作表
            XSSFSheet sheet = workbook.createSheet("封样桶信息");
            
            // 创建表头行
            XSSFRow headerRow = sheet.createRow(0);
            headerRow.createCell(0).setCellValue("企业编码");
            headerRow.createCell(1).setCellValue("材料类型");
            headerRow.createCell(2).setCellValue("适用月份");
            headerRow.createCell(3).setCellValue("申请时间");
            headerRow.createCell(4).setCellValue("瓶盖码");
            headerRow.createCell(5).setCellValue("瓶身码");
            
            // 写入数据行
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            int rowNum = 1;
            for (SealSampleInfo info : sealSampleInfos) {
                XSSFRow row = sheet.createRow(rowNum++);
                row.createCell(0).setCellValue(info.getCompanyCode());
                row.createCell(1).setCellValue(info.getMaterialType());
                row.createCell(2).setCellValue(info.getApplicableMonth());
                row.createCell(3).setCellValue(info.getApplyTime());
                row.createCell(4).setCellValue(info.getBottleCapCode());
                row.createCell(5).setCellValue(info.getBottleBodyCode());
            }
            
            // 自动调整列宽
            for (int i = 0; i < 6; i++) {
                sheet.autoSizeColumn(i);
            }
            
            // 写入文件
            workbook.write(outputStream);
            System.out.println("Excel文件导出成功，路径：{}" + filePath);
            return filePath;
        } catch (Exception e) {
            log.error("导出Excel文件失败", e);
            throw new RuntimeException("导出Excel文件失败：" + e.getMessage());
        }
    }
}